<!-- 组织-组织机构管理-法律实体 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title"> </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space direction="vertical">
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="请输入姓名"
            search-button
            v-model="searchVal"
            @search="onSearch"
            @press-enter="onSearch"
          >
            <template #button-icon>
              <icon-search />
            </template>
          </a-input-search>
        </a-space>
      </template>
      <template #right>
        <a-space size="medium">
          <a-button type="primary" @click="add(null)">新增黑名单</a-button>
          <a-button type="outline" status="danger" @click="del(null)"
            >批量删除</a-button
          >
          <!-- <a-button type="outline">批量操作</a-button> -->
        </a-space>
      </template>
    </ConditionBox>

    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column title="序号" :width="80">
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.dataIndex"
        :title="item.title"
        :data-index="item.dataIndex"
        :width="item.width"
      >
        <template #cell="{ record }" v-if="item.dataIndex === 'name'">
          <span
            @click="goDetail(record)"
            :style="{
              cursor: record.type === 1 ? 'pointer' : ''
            }"
          >
            {{ record.name }}
          </span>
        </template>
        <template #cell="{ record }" v-if="item.dataIndex === 'departmentId'">
          {{
            dataList?.organizationList.find(
              (item: any) => item.id == record.departmentId
            )?.name || '---'
          }}
        </template>
        <template #cell="{ record }" v-if="item.dataIndex === 'positionId'">
          {{
            dataList?.positionList.find(
              (item: any) => item.id == record.positionId
            )?.name || '---'
          }}
        </template>
      </a-table-column>

      <!-- <a-table-column :width="100" dataIndex="name" title="是否开启">
        <template #cell="{ record }">
          <a-switch v-model="record.IsEnable" /> </template
      ></a-table-column> -->
      <a-table-column
        dataIndex="workPlace"
        title="操作"
        fixed="right"
        :width="100"
      >
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="headerSettingVisible = !headerSettingVisible"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <div style="float: left; display: flex">
            <a-tooltip content="详情">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goDetail(record)"
                v-if="record.type === 1"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <icon-font
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record.id)"
              >
                <icon-font
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </div> </template
      ></a-table-column>
    </TableTurn>
  </ContentCard>
  <AddBlackList
    v-model:visible="addVisible"
    :data="currData"
    @blacklistAddEmit="blacklistAddEmit"
  />
  <FormHeaderSetting
    v-model:visible="headerSettingVisible"
    title="黑名单表头设置"
    :resultList="resultList"
    :forbidList="forbidList"
    :orginHeaderList="orginHeaderList.headerListCode"
    @headerSave="headerSave"
  />
</template>

<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue';
import AddBlackList from './Components/AddBlacklist/index.vue';
import {
  PostBlacklist,
  PutBlacklist,
  GetBlacklist,
  DelBlacklist
} from '@/apis/management/human/humanChange/blacklist';
import {
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import { getControlValue } from '@/utils/control';
import { getAgeFromIdCard } from '@/utils/utils';
import { getListData, IneedSwitchArr } from '@/utils/getAllSwitchListData';
import { cloneDeep } from 'lodash';

const router = useRouter();
const userId = +(localStorage.getItem('userId') as string);
const title = '黑名单管理列表';

const modelVisible = ref(false);
let tableRef = ref(); // 储存table的ref
const addLegalEntityData = ref();
const LegalEntityTitle = ref();
let type = ref(''); // 判断用户点击查看新增、详情还是编辑
/* 储存选择的数据 */

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

let searchVal = ref(''); // 搜索框值

let tableSettingVisible = ref(false); // 是否显示表头设置

// 需要转化的数据
const needSwitchArr: IneedSwitchArr[] = ['organization', 'position'];
let originTableData = ref([]); // 储存原始从后端拿回来的表格数据
// 获取表格数据
const getTableData = async (page: any) => {
  try {
    const res = await GetBlacklist({
      ...page,
      name: searchVal.value
    });
    originTableData.value = cloneDeep(res.content);
    res.content = res.content.map((item: any) => {
      // 内部人员
      if (item.type === 1) {
        // 司龄
        item.siLing =
          item.ctlValue.find(
            (el: any) => el.ctlCode === 'CC14DBDACA73B441E84106FA586B08645'
          )?.ctlValue || '---';
        // 年龄
        item.age = getAgeFromIdCard(item.idNum) || '---';
        // 入职时间
        item.entryTime =
          item.ctlValue.find(
            (el: any) => el.ctlCode === 'CB3B0DDCEBCE94567BD908641A521100E'
          )?.ctlValue || '---';
      }
      // 外部人员
      else if (item.type === 2) {
        item.siLing = '---';
        item.entryTime = '---';
        item.age = getAgeFromIdCard(item.idNum) || '---';
      }
      for (let key in item) {
        if (!item[key] || item[key] == '') {
          item[key] = '---';
        }
      }
      console.log('=======item=============================');
      console.log(item);
      console.log('====================================');
      return {
        ...item
      };
    });

    // flatData.value = flatTree(res);
    // console.log(flatData.value.length);
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 表头设置所有表头(默认不能移动的表头要放在最前面)
const resultList = [
  {
    title: '姓名',
    dataIndex: 'name',
    width: 120
  },
  {
    title: '工号',
    dataIndex: 'jobNum',
    width: 200
  },
  {
    title: '前部门',
    dataIndex: 'departmentId',
    width: 80
  },
  {
    title: '前职位',
    dataIndex: 'positionId',
    width: 150
  },
  {
    title: '证件类型',
    dataIndex: 'idType',
    width: 100
  },
  {
    title: '证件号码',
    dataIndex: 'idNum',
    width: 200
  },

  {
    title: '手机号码',
    dataIndex: 'mobile',
    width: 200
  },
  {
    title: '年龄',
    dataIndex: 'age',
    width: 100
  },
  {
    title: '司龄',
    dataIndex: 'siLing',
    width: 100
  },
  {
    title: '入职时间',
    dataIndex: 'entryTime',
    width: 200
  },
  {
    title: '黑名单原因',
    dataIndex: 'reason',
    width: 200
  }
];
const addHeader = async () => {
  try {
    await PostHeaderSetting({
      userId,
      ownerFuncType: 16, // 黑名单列表写死16
      headerListCode: resultList.map((item: any) => item.dataIndex).join(',')
    });
    const headerRes = await GetHeaderSetting({
      ownerFuncType: 16,
      userId
    });
    orginHeaderList.value = headerRes;
  } catch (error: unknown) {
    console.log(error);
  }
};
let forbidList = ref(['name', 'phone', 'reason']); // 禁止移动的表头
let orginHeaderList = ref([]); // 后端传过来的表头
let headerSettingVisible = ref(false);
let headerSetting = ref<any>([]); // 当前的表头数据
let dataList = ref({}); // 储存所有要转换的数据
// 获取法律类型数据
const getData = async () => {
  const [headerRes, dataListRes]: any = await Promise.all([
    GetHeaderSetting({
      ownerFuncType: 16,
      userId
    }),
    getListData(needSwitchArr)
  ]);
  orginHeaderList.value = headerRes;
  dataList.value = dataListRes;
  console.log('====dataList================================');
  console.log(dataList.value);
  console.log('====================================');
  if (headerRes.headerListCode.length < 1) {
    addHeader();
  }
  headerSetting.value = resultList;
};
getData();

// 在表格上显示的表头
const selectedHeader = computed(() => {
  let selectedHeaders: any[] = [];
  if (orginHeaderList.value?.id) {
    let temp = headerSetting.value.filter((el: any) =>
      orginHeaderList.value?.headerListCode.includes(el.dataIndex)
    );

    let defaultHeaders = temp.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.dataIndex);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders = defaultHeaders;
    selectedHeaders.sort((a, b) => a.sort - b.sort);
    console.log('====================================');
    console.log(selectedHeaders);
    console.log('====================================');
    // // 将名称移到最前面
    const nameHeaderIndex = selectedHeaders.findIndex(
      (header) => header.dataIndex === 'name'
    );
    if (nameHeaderIndex !== -1) {
      selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
    }
  }

  return selectedHeaders;
});

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.dataIndex).join(',');
    await PutHeaderSetting({
      id,
      userId,
      ownerFuncType: 16,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 搜索框
const onSearch = () => {
  tableRef.value.loadData({
    pageNumber: 0,
    pageSize: -1
  });
};

let addVisible = ref(false); // 添加弹窗
let currData = ref({});
const add = (record: any | null) => {
  currData.value = record;
  addVisible.value = true;
};

// 新增黑名单自定义事件
const blacklistAddEmit = async (record: any) => {
  try {
    if (record?.id) {
      await PutBlacklist(record);
    } else {
      await PostBlacklist(record);
    }
    refresh();
    //
  } catch (error: unknown) {
    console.log(error);
  }
};

let singleSelectId = 0; // 储存单个id
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

// 详情
const goDetail = (record: any) => {
  // 如果是外部人员则不能跳转到花名册
  if (record.type === 2) {
    return;
  }
  router.push({
    name: 'HumanRosterDetail',
    query: {
      id: record.createBy,
      isBlacklist: 1
    }
  });
};

// 编辑
const goEdit = (id: number) => {
  currData.value = originTableData.value.find((item) => item.id === id);
  addVisible.value = true;
};

// 删除一项
const del = async (id: number | null) => {
  try {
    if (!id) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              await DelBlacklist({
                ids: selectedList.value
              });
              tableRef.value.selectedList = [];
              refresh();
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      await DelBlacklist({
        ids: [id]
      });
      tableRef.value.selectedList = [];
      refresh();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style lang="less" scoped>
.container {
  padding: 10px 20px;
  .header {
  }
  .main {
    margin-top: 20px;
  }
}
</style>
